<template>
  <div class="container">
    <el-card style="margin: 10px">
      <!-- 头部搜索 -->
        <el-row>
          <el-col :span="18">
            <el-form :model="queryList" :inline="true" class="demo-form-inline">
              <el-form-item style="margin-left: 20px" label="关键字">
                <el-input v-model="queryList.keyword" size="small" placeholder="根据文章标题搜索"></el-input>
              </el-form-item>
              <el-form-item style="margin-left: 20px" label="状态">
                <el-select  v-model="queryList.state"  size="small" placeholder="请选择">
                  <el-option label="启用" value="1" />
                  <el-option label="禁用" value="0" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button size="small" @click="Clear">清除</el-button>
                <el-button size="small" type="primary" @click="onSubmit">搜索</el-button>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="6">
            <el-row type="flex" justify="end">
              <el-button size="small" type="success" icon="el-icon-edit" @click="addShowDialog = true">新增技巧</el-button>
            </el-row>
          </el-col>
        </el-row>
        <!-- 消息提示 -->
        <el-row>
          <el-alert :title="`数据一共 ${counts} 条`" :closable="false" type="info" show-icon />
        </el-row>
        <!--表格 -->
        <el-row style="margin-top: 20px">
          <el-table :data="articlesList" border style="width: 100%">
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column label="文章标题" width="400">
              <template slot-scope="scope">
                {{ scope.row.title }}
                <i v-if="scope.row.videoURL" class="el-icon-film" aria-hidden="true" style="color: blue; font-size: 18px" @click="openVideo(scope.row.videoURL)" />
                </template>
            </el-table-column>
            <el-table-column label="阅读数" prop="visits"/>
            <el-table-column label="录入人" prop="username" />
            <el-table-column label="录入时间" prop="createTime">
              <template slot-scope="scope">
                {{ scope.row.createTime | formatTime }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100" prop="state" />
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button
                type="text"
                size="small"
                @click="handlePreview(scope.row)"
                >预览</el-button>
                <el-button
                type="text"
                size="small"
                @click="handleState(scope.row)"
                >{{ scope.row.state === 1 ? '禁用' : '启用' }}</el-button>
                <el-button type="text" size="small" @click="handleEdit(scope.row)"
                >修改</el-button>
                <el-button
                type="text"
                size="small"
                @click="handleDelete(scope.row)"
                :disabled="scope.row.state === 1 ? true : false"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <!-- 分页 -->
        <el-row style="margin-top: 20px" type="flex" justify="end">
          <el-pagination
            background
            :hide-on-single-page="totalPage === 1 ? true : false"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="counts" />
        </el-row>
      </el-card>
      <!-- 视频区域 -->
      <el-dialog id="videoDialog" class="video" width="40%" :visible="videoShowDialog" :show-close="false">
        <el-button id="closeBtn" @click="closeVideo" type="info" icon="el-icon-close" circle></el-button>
        <video ref="videoRef" :src="videoUrl" width="100%" autoplay controls></video>
      </el-dialog>
    <!-- 新增/修改弹窗 -->
    <ArticlesAdd
      :articleForm.sync="articleForm"
      :addShowDialog.sync="addShowDialog"
      @updateArticleList="getArticleList"
      :currentPage.sync="currentPage"
    ></ArticlesAdd>
    <!-- 预览文章 -->
    <ArticlesPreview
      :previewDialog.sync="previewDialog"
      :previewItem="previewItem"
    ></ArticlesPreview>
  </div>
</template>

<script>
import moment from 'moment'
import { list, detail, remove, changeState } from '@/api/hmmm/articles.js'
import ArticlesAdd from '@/module-hmmm/components/articles-add'
import ArticlesPreview from '@/module-hmmm/components/articles-preview'
export default {
  name: 'Articles',
  components: {
    ArticlesAdd,
    ArticlesPreview
  },
  filters: {
    // 格式化时间
    formatTime (val) {
      return moment(val).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  data () {
    return {
      queryList: {
        keyword: undefined,
        state: undefined
      },
      // 总条数
      counts: 0,
      pagesize: 10,
      currentPage: 1,
      totalPage: 0,
      // 视频路径
      videoUrl: '',
      // 文章列表请求返回数组
      articlesList: [],
      // 新增弹框
      addShowDialog: false,
      previewDialog: false,
      videoShowDialog: false,
      previewItem: {},
      articleForm: {
        title: undefined,
        articleBody: undefined,
        videoURL: undefined,
        id: undefined
      }
    }
  },
  mounted () {
    this.getArticleList()
  },
  methods: {
    // 获取文章的列表
    async getArticleList () {
      const { data } = await list({ page: this.currentPage, pagesize: this.pagesize, ...this.queryList })
      this.articlesList = data.items
      this.counts = data.counts
    },

    // 清除筛选条件
    Clear () {
      this.queryList.keyword = ''
      this.queryList.state = null
      this.getArticleList()
    },

    // 点击按钮根据筛选条件搜索
    onSubmit () {
      this.currentPage = 1
      this.getArticleList()
    },

    // 启用禁用设置
    async handleState (row) {
      try {
        row.state = Number(!row.state)
        await changeState(row)
        this.$message.success('操作成功')
        this.getArticleList()
      } catch (e) {
        this.$message.error('操作失败')
      }
    },

    // 修改按钮
    async handleEdit (row) {
      this.addShowDialog = true
      const { data } = await detail(row)
      this.articleForm = data
    },

    // 点击删除
    handleDelete (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await remove(row)
        this.$message.success('删除成功')
        // 删除的时候，判断一下，如果当前页比counts/pagesize还要大，那当前页--，重新获取一次页数。
        // 如果22条数据， 当前页在第三页。删除一条，21/10, 2.1，还是需要3页。
        // 如果21条数据，当前页第3页，删除一条，20/10， 2页。只需要两页。
        // 所以要用Math.ceil
        this.counts--
        if (this.currentPage > Math.ceil(this.counts / this.pagesize)) {
          this.currentPage--
        }
        this.getArticleList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 预览弹窗
    handlePreview (row) {
      this.previewDialog = true
      this.previewItem = row
    },

    // 点击开启video
    openVideo (url) {
      this.videoShowDialog = true
      this.videoUrl = url
    },

    // 点击关闭video
    closeVideo (row) {
      this.videoShowDialog = false
      this.videoUrl = row
    },

    // 条数
    handleSizeChange (val) {
      this.pagesize = val
      this.getArticleList()
    },

    // 页数
    handleCurrentChange (val) {
      this.currentPage = val
      this.getArticleList()
    }
  }
}
</script>

<style scoped lang='less'>
  #videoDialog {
  ::v-deep.el-dialog__header {
    background-color: transparent;
    height: 0 !important;
    padding: 0;
  }
  ::v-deep.el-dialog__body {
    padding: 0;
    height: 0;
  }
  #closeBtn {
    position: absolute;
    top: -50px;
    left: 50%;
    transform: translate(-11px);
    background-color: rgb(60, 57, 57);
    opacity: 0.6;
  }
}
</style>
